package engine.newUi
{
	import engine.control.MenuList;
	import engine.control.NxTablePageTurner;
	import engine.data.ModelLocator;
	import engine.net.datatype.WString;
	import engine.net.event.CustomMsgEvent;
	import engine.net.messages.CustomToClientFlag;
	import engine.net.messages.CustomToServerFlag;
	import engine.net.mgr.SystemSender;
	import engine.ui.AlertUI;
	
	import flash.events.MouseEvent;
	
	import newx.com.config.StaticIni;
	import newx.com.control.button.NxButton;
	import newx.com.control.table.NxTabelPos;
	import newx.com.control.table.NxTableEvent;
	import newx.com.control.table.TableCellFactory;
	import newx.com.control.window.NxWindowEvent;

	/**
	 * 
	 * @author gaoyq
	 * 
	 */
	public class FamilyLogic
	{
		private var _ui:FamilyUI;
		/**数据模型*/
		private 	var _model			:ModelLocator;
		public static var _self:FamilyLogic;
		/**数据列数***/
		private var _dataCount:int = 6;
		
		/**翻页管理工具*/
		private var _pageTurner: NxTablePageTurner;
		/***当前选中的帮派名字**/
		private var _familyName:String ="";
		
		/**自定义cell按钮生产**/
		private var _tableCellFactory : TableCellFactory;
		/**已经申请过的帮派名称合集**/
		private var isAddFamilyNames : Array = [];
		/**当前行帮派数据**/
		private var _curFamilyInfo:Object;
		
		public function FamilyLogic()
		{
			
		}


		public static function getInstance():FamilyLogic
		{
			if(_self == null)
			{
				_self =new FamilyLogic();
			}
			return _self;
		}
		
		
		public function uiinit():void
		{
			_model = ModelLocator.getInstance();
			if(_curFamilyInfo == null){
				_curFamilyInfo = new Object;
			}
			//家族排行榜
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_GUILD_OPENRANKINFO),onFamilyHandle);
			_model.addEventListener(String(CustomToClientFlag.SERVER_CUSTOMMSG_ADD_GUILD_SUCCESS),onFamilyCreatOkHandle);
			
			_pageTurner	=	new NxTablePageTurner( ui.btn_pre, ui.btn_next, ui.tab_list, ui.lab_page );
		}
		
		private function onFamilyCreatOkHandle(e:CustomMsgEvent):void
		{
			ui.hide();
			var flagT	:String	=	_model.scene.Role.GetProperties("GuildName");
			if(0 < flagT.length)
			{
				//查看公会详细信息
				SystemSender.getInstance().CustomMsg(
					CustomToServerFlag.CLIENT_CUSTOMMSG_GET_GUILD_INFO ,new WString(flagT));
			}
		}
		
		
		/**
		 *获取家族排行信息 
		 * @param e
		 * 
		 */
		private function onFamilyHandle(e:CustomMsgEvent):void
		{
			var dataList:Array = e.pList;
			dataList.shift();
			var datalen:int = e.pList.length;
			var rank:int = 0;
			var dataPrivater:Array = []; 
			var sortArr:Array = [];
			if(datalen<_dataCount)return;
			for( var i : int = 0; i < datalen; i+= _dataCount )
			{
				var vo:Object = new Object();
				rank ++;
				vo.rank = rank < 1 ? StaticIni.getSwfLangStr( "Common_Null" ) : rank.toString();
//				vo.rank = dataList[i]
				vo.name	= dataList[i];
				vo.master	= dataList[i+1];
				vo.level	= dataList[i+3];
				vo.count	= dataList[i+2]+"/"+StaticIni.getIniVar("familyUP_"+vo.level,"count");
				vo.guideRand= dataList[i+4];
//				vo.state	= dataList[i+5];//申请状态
//				vo.castle	= ""//StaticIni.getSwfLangStr( dataList[i+5].replace(",", "_npcscene_") );
//				vo.prestige	= dataList[i+5]
//				dataPrivater.push( vo );
				sortArr.push(vo);
				
			}
			sortArr.sortOn("guideRand",Array.NUMERIC);
			for(var j:int = 0;j<sortArr.length;j++)
			{
				var vo1:Object = sortArr[j];
				vo1.rank = j+1;
				dataPrivater.push( [{label:vo1.rank},{label:vo1.name,data:vo1.name},{label:vo1.master},{label:vo1.level},{label:vo1.count}]);
			}
			createButtonCell();
			ui.tab_list.dataProvider = dataPrivater;
			_pageTurner.onPageDis();
		}
		
		/**
		 *创建自定义控件 查看按钮 申请按钮
		 * 
		 */
		private function createButtonCell():void
		{
			var button :　NxButton = new NxButton();
			button.skin = "Button_20";
			button.width = 40;
			button.label = StaticIni.getSwfLangStr("UIString_1000368");
		    if (_model.scene.Role.getPlayerGuild() == "")
			{
				var applybtn :　NxButton = new NxButton();
				applybtn.skin = "Button_20";
				applybtn.width = 40;
				applybtn.label = StaticIni.getSwfLangStr("UIString_1000738");
				_tableCellFactory = new TableCellFactory(_ui.tab_list, _ui.windowBG, button, 5, false, applybtn, 10);
			}else
			{
				_tableCellFactory = new TableCellFactory(_ui.tab_list, _ui.windowBG, button, 5, true);
			}
			_tableCellFactory.TablePageChangeData = tablePageChangeData;
		}
		
		private function tablePageChangeData():void
		{
			var maxPageCount : int = _ui.tab_list.pageLinesConut;
			for(var i:int = 0;i<maxPageCount;i++)
			{
				var pn:String = _ui.tab_list.getItemFrom(
					new NxTabelPos(i+_ui.tab_list.currentPage*maxPageCount));
				var cellButton:NxButton;
				if(pn != "" && pn != null && _tableCellFactory.ArrTabelCell != null)
				{
					cellButton = _tableCellFactory.ArrTabelCell[i];
					if (_model.scene.Role.getPlayerGuild() == "")
					{
						var applyBtn:NxButton;
						applyBtn	= _tableCellFactory.ArrTabelCell[i + maxPageCount];
						if(cellButton == null)
							continue;
						applyBtn.data.Properties["index"] = i+_ui.tab_list.currentPage*maxPageCount;
						applyBtn.addEventListener(MouseEvent.CLICK, onClickAddFamily);
					}else
					{
						if(cellButton == null)
							continue;
					}
					cellButton.data.Properties["index"] = i+_ui.tab_list.currentPage*maxPageCount;
					cellButton.addEventListener(MouseEvent.CLICK,onClickQueryFamilyBtn);
				}
			}
		}
		
		public function BeforeShow():void
		{
//			ui.tab_list.titleLabels = [ "Common_Sort", "UIStr_1000714", "UIStr_1000491", "UIStr_1000413", "UIStr_1000493", "UIStr_1000716" ];
			_familyName == "";
			ui.btn_addfamily.enabled = false;
			ui.btn_addfamily.visible = false;
			var flagT	:String	=	_model.scene.Role.GetProperties("GuildName");
			if(0 < flagT.length)
			{
				ui.btn_createGuild.visible = false;
				ui.btn_addfamily.visible = false;
			}
			else
			{
				ui.btn_createGuild.visible = true;	
//				ui.btn_addfamily.visible = true;
			}
			SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_GET_GUILDINFO,0);
			addListenter();
		}
		
		public function AfterHide():void
		{
			removeListenter();
			if(_tableCellFactory)
				_tableCellFactory.destroy();
		}
		
		private function onClickCloseHandle(e:NxWindowEvent):void
		{
			ui.hide();
		}
		//创建家族
		private function onClickCreateGuildHandle( evt : MouseEvent ):void
		{
			var	title		:String			=	StaticIni.getSwfLangStr("31100");
			var descTitle	:String			=	StaticIni.getSwfLangStr("UIStr_1000486");
			var	iniDesc		:String			=	StaticIni.getSwfLangStr("UIStr_1000485");
			var	yesBtn		:String			=	StaticIni.getSwfLangStr("AlertEx_16");
			var	noBtn		:String			=	StaticIni.getSwfLangStr("AlertEx_1");
			AlertUI.showAlertEx(title,iniDesc,[yesBtn,noBtn],AlertUI.YES|AlertUI.NO,createGuild,null,true,300,150,descTitle,true);
			
			//是创建帮派的时候，提示文字需要支持 鼠标移动到后，删除文字
			
			function createGuild( type:int, str:String, clickData:* ):void
			{
				if(AlertUI.YES == type )
				{
					//首字母非法提示
					if(isIllegalLetter(str.charAt(0)))
					{
						AlertUI.showAlert(title,StaticIni.getSwfLangStr("UIString_1000623"),AlertUI.OK);
						return;
					}
					SystemSender.getInstance().CustomMsg(CustomToServerFlag.CLIENT_CUSTOMMSG_GUILD_CREATE,
						new WString(str),1,new WString("s"));
				}
			}
		}
		
		
		/**
		 * 是否是非法字符
		 * @param str
		 * @return 
		 */		
		private function isIllegalLetter(str:String):Boolean
		{
			var arr:Array=["_","0","1","2","3","4","5","6","7","8","9"];
			for(var i:int=0;i<11;i++)
			{
				if(str==arr[i])
				{
					return true;
				}
			}
			return false;
		}
		
		private function onClickTableHandle( evt : NxTableEvent ):void
		{
			if(!evt.lineArrData)
			{
//				MenuList.hide();
				_familyName = "";
				ui.btn_addfamily.enabled = false;
				return;
			}
			var data : Object = evt.lineArrData[1]["data"];
			
			if(!data)
			{
				_familyName = "";
				ui.btn_addfamily.enabled = false;
				return;
			}
			_familyName = String(data);
//			ui.btn_addfamily.enabled = !isAdd(_familyName);
			ui.btn_addfamily.enabled = true;
//			MenuList.ShowMenu([ StaticIni.getSwfLangStr("UIStr_1000419") ], onFamilyMenuListClick, data );
//			function onFamilyMenuListClick( index:int, name:String ):void
//			{
//				SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMSG_GUILD_REQUEST_JOIN_GUILD, new WString( name ) );
//			}
		}
		
		/**
		 *点击查看帮派 
		 * @param event
		 * 
		 */
		private function onClickQueryFamilyBtn(event:MouseEvent):void
		{
			var index : int = event.target.data.Properties["index"];
			var familyName : String = _ui.tab_list.getItemDataFrom(new NxTabelPos(index,1)) as String;
			if(familyName == "")return;
			SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMSG_KNOW_OTHER_GUILD,new WString(familyName));
		}
		
		/**
		 *加入帮派 
		 * @param e
		 * 
		 */
		private function onClickAddFamily(e:MouseEvent):void
		{
			var index : int = e.target.data.Properties["index"];
			var familyName : String = _ui.tab_list.getItemDataFrom(new NxTabelPos(index,1)) as String;
			if(familyName == "")return;
//			if(!isAdd(_familyName))isAddFamilyNames.push(_familyName);
//			ui.btn_addfamily.enabled = !isAdd(_familyName);
			var btn:NxButton	= e.currentTarget as NxButton;
			if(btn.label	== StaticIni.getSwfLangStr("UIString_1000738")){
				SystemSender.getInstance().CustomMsg( CustomToServerFlag.CLIENT_CUSTOMMSG_GUILD_REQUEST_JOIN_GUILD, new WString( familyName ) );
			}
		}
		
		/**
		 *是否在已申请过的加入帮派中
		 * @param familyName
		 * @return 
		 * 
		 */
		private function isAdd(familyName : String):Boolean
		{
			for each(var names : * in isAddFamilyNames)
			{
				if(names == familyName)
				{
					return true;
				}
			}
			return false;
		}
		
		private function onClickBtn(e:MouseEvent):void
		{
			ui.btn_addfamily.enabled = false;
		}
		
		/**
		 *添加监听 
		 * 
		 */
		private function addListenter():void
		{
			ui.btn_addfamily.addEventListener(MouseEvent.CLICK,	onClickAddFamily);
			ui.btn_createGuild.addEventListener(MouseEvent.CLICK,		onClickCreateGuildHandle);
			ui.windowBG	.addEventListener(	NxWindowEvent.WINDOW_CLOSE,	onClickCloseHandle);
			ui.tab_list .addEventListener(	NxTableEvent.TABLE_CLICK,	onClickTableHandle);
			ui.btn_next.addEventListener(MouseEvent.CLICK,onClickBtn);
			ui.btn_pre.addEventListener(MouseEvent.CLICK,onClickBtn);
			_pageTurner.addEventListener();
		}
		
		/**
		 *移除监听 
		 * 
		 */
		private  function removeListenter():void
		{
			ui.btn_addfamily.removeEventListener(MouseEvent.CLICK,	onClickAddFamily);
			ui.btn_createGuild.removeEventListener(MouseEvent.CLICK,		onClickCreateGuildHandle);
			ui.windowBG	.removeEventListener(	NxWindowEvent.WINDOW_CLOSE,	onClickCloseHandle);
			ui.tab_list .removeEventListener(	NxTableEvent.TABLE_CLICK,	onClickTableHandle);
			ui.btn_next.removeEventListener(MouseEvent.CLICK,onClickBtn);
			ui.btn_pre.removeEventListener(MouseEvent.CLICK,onClickBtn);
			_pageTurner.removeEventListener();
		}
		
		public function get ui():FamilyUI
		{
			if(_ui==null)
			{
				_ui	=	new FamilyUI();
			}
			return _ui
		}
	}
}